var amapFile = require('../../libs/amap-wx.js');
var config = require('../../libs/config.js');
var lonlat;
var city;
Page({
  data: {
    tips: {}
  },
  onLoad: function(e){
    lonlat = e.lonlat;
    city = e.city;
  },
  //优化：只执行最后一次即防抖
  // debounce: function(fn, time) {
  //   let timer;
  //   return function(...args) {
  //       if (timer) {
  //           clearTimeout(timer);
  //       }
  //       timer = setTimeout(() => {
  //           fn.apply(this, args);
  //       }, time);
  //   };
  // },
  // bindInput: function(e) {
  //   var that = this;
  //   var keywords = e.detail.value; 
  //   var key = config.Config.key;
  //   var myAmapFun = new amapFile.AMapWX({key: key});
    
  //   const fetchTips = () => {
  //       myAmapFun.getInputtips({
  //           keywords: keywords,
  //           location: lonlat,
  //           city: city,
  //           success: function(data) {
  //               console.log('data：', data);
  //               if (data && data.tips) {
  //                   that.setData({
  //                       tips: data.tips
  //                   });
  //               }
  //           }
  //       });
  //   },
  //   this.debounce(fetchTips, 5000)();  // 调用防抖函数
  // },

  bindInput: function(e){
    var that = this;
    var keywords = e.detail.value; 
    var key = config.Config.key;
    var myAmapFun = new amapFile.AMapWX({key: key});
    myAmapFun.getInputtips({
      keywords: keywords,
      location: lonlat,
      city: city,
      success: function(data){
        if(data && data.tips){
          that.setData({
            tips: data.tips
          });
        }
      }
    })
  },
  bindSearch: function(e){
    // console.log(e);
    var keywords = e.target.dataset.keywords;
    // console.log('location：',this.data.tips[0].location)
    const locationArray = this.data.tips[0].location.split(',');
    const keywordsLongitude = parseFloat(locationArray[0]);
    const keywordsLatitude = parseFloat(locationArray[1]);
    var url = '../poi/poi?keywords=' + keywords + '&latitude=' + keywordsLatitude + '&longitude=' + keywordsLongitude;
    // console.log(url);
    wx.redirectTo({
      url: url
    })
  }
})